#include "bhxjglsphere.h"

BHXJGLSphere::BHXJGLSphere():BHXJGLModel()
{

}

void BHXJGLSphere::Init(BHXJGLFUN *glcore,unsigned int latnum,unsigned int lngnum)
{
    this->gl=glcore;

    //圆，用来组成经纬
    auto arr=BHXJGLModelHelper::getCirclePoints(lngnum);
    {
        //将点扭转至水平姿态
        glm::mat3 matc;
        matc[0]=glm::vec3(1,0,0);
        matc[1]=glm::vec3(0,0,-1);
        matc[2]=glm::vec3(0,1,0);
        for(unsigned int i=0;i<arr->size();++i)
        {
            arr->at(i)=matc* arr->at(i);
        }
    }


    //纬度分割点 确定有多少个圆
    auto arrlat=BHXJGLModelHelper::getArcPoints(latnum,180);
    arrlat->front().x=0;
    arrlat->front().y=1;
    arrlat->back().x=0;
    arrlat->back().y=-1;

    BHXJGLMesh *m=new BHXJGLMesh();
    BHXJGLVertex v;
    for(unsigned int lati=0;lati<arrlat->size();++lati)
    {
        for(unsigned int i=0;i<arr->size();++i)
        {
            glm::vec3 &vlat=arrlat->at(lati);
            glm::vec3 &vlng=arr->at(i);
            v.position = glm::vec3(vlng.x*vlat.x,vlat.y,vlng.z*vlat.x);
            v.texcoodr=glm::vec2(static_cast<float>(i)/lngnum,1.0f-static_cast<float>(lati)/latnum);

            m->vertices.push_back(v);
        }
    }

    for(unsigned int i=0;i<latnum;++i)
    {
        if(i==0)
        {
            BHXJGLModelHelper::addConeToMesh(m,i*arr->size(),(i+1)*arr->size(),lngnum);
            continue;
        }
        if(i==latnum-1)
        {
            BHXJGLModelHelper::addConeToMesh(m,(i+1)*arr->size(),i*arr->size(),lngnum,BHXJBack);
            continue;
        }
        BHXJGLModelHelper::addStripeToMesh(m,i*arr->size(),(i+1)*arr->size(),lngnum);
    }

    //加入网格并初始化
    this->meshes.push_back(m);
    m->Init(this->gl);

    BHXJGLTexture2D *texture=new BHXJGLTexture2D();
    this->textures.push_back(texture);
    m->textures.push_back(texture);
    texture->Init(gl,"./texture/125.jpg");

}
